<?php
include 'portlet_header.php';
if (getParameter("operation")!=null) $operation=getParameter("operation");
if (getParameter("container")!=null) { $container=getParameter("container"); if ( $container=="") $container="container1";} else $container="container1";

if (getParameter("portlet")!=null) $portlet=getParameter("portlet");
if (getParameter("portletId")!=null) $portletId=getParameter("portletId");
if (getParameter("pageId")!=null) $pageId=getParameter("pageId");
//if (getParameter("porltetId")) $porltetId=getParameter("porltetId")!=null;
//if (getParameter("coupleId")) $coupleId=getParameter("coupleId")!=null;
if (getParameter("order")!=null) $order=getParameter("order");
if (getParameter("portalId")!=null) $portalId=getParameter("portalId");

if ($operation=="addEditLabel")
{
	
	$label=getParameter("label");
	$objectId=getParameter("objectId");
	insertObjByKey("portal_object_edit_labels","objectId","label_".$LANG,"labelName","orderCmpnt",$objectId,$label,safeDomName($label),getMaxOrderObject("portal_object_edit_labels",null,"objectId",$objectId));
	
}elseif ($operation=="ajaxSelect")
{
	

	$value=getParameter("value");
	$filter=getParameter("filter");
	$filter=str_replace("\'", "'", $filter);
	
	$table=getParameter("table");

	$sSql = "SELECT $value FROM $table WHERE $filter";
	
	//echo $sSql;
	$rs=$GLOBALS["conn"]->Execute($sSql);
	
	echo $rs->fields[$value];
	
	
	
	
}elseif ($operation=="ajaxJsonSelect")
{
	$key=getParameter("key");
	$value=getParameter("value");
	$filter=getParameter("filter");
	$table=getParameter("table");
	
	$id = getParameter("id");
	$sSql = "SELECT * FROM $table WHERE $filter =  $id";
	
	//echo $sSql;
	$rs=$GLOBALS["conn"]->Execute($sSql);
	
	$json = array();
	
	$json[] = array(
			'key' => "none",
			'value' => "" // Don't you want the name?
	);
		while ($rs && !$rs->EOF)  {
	


		$json[] = array(
				'key' => $rs->fields[$key],
				'value' => $rs->fields[$value] // Don't you want the name?
		);
		
		$rs->MoveNext();
	}
	
	// modify your http header to json, to help browsers to naturally handle your response with
	header('Cache-Control: no-cache, must-revalidate');
	header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
	header('Content-type: application/json');
	
	echo json_encode($json);	
	
}elseif($operation=="loadautocomplete")
{
	
	
	if(isset($_GET['term'])) {
		$q = htmlentities($_GET['term']); // protection
			
		$results = array();
		$key=getParameter("key");
		$value=getParameter("value");
		$filter=getParameter("filter");
		$table=getParameter("table");
	
	
		$sSql = "SELECT
		$table.$key,
		$table.$value as lib
		FROM
		$table
		WHERE $filter and UPPER($value) LIKE UPPER('%". $q ."%') LIMIT 0, 10";
	
		//echo $sSql;
	
	
	
		$rs=$GLOBALS["conn"]->Execute($sSql);
	
			
		while ($rs && !$rs->EOF)  {
	
	
	
			//echo '"'.$rs->fields["id"].'": "'.$rs->fields["lib"].'"'.'\n';
	
			$results[] = array(
					'label'    => $rs->fields["lib"],
					'value' => $rs->fields[$key]
	
			);
			$rs->MoveNext();
	
	
		}
	
	
			
		// modify your http header to json, to help browsers to naturally handle your response with
		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');
	
		echo json_encode($results);
	
	}
	
}elseif ($operation=="ajaxAdd")
{
	
	insertObjByKey($table,"contentId","tagId",$id,$tagId);
	

	
}elseif ($operation=="getportalobjects")
{

	if(isset($_GET['term'])) {
		$q = htmlentities($_GET['term']); // protection
			
		$results = array();

$table=getObjByKey("portal_objects","name","id",getParameter("objectname"));


		$sSql = "SELECT
$table.id,
$table.name as lib
FROM
$table
WHERE UPPER(name) LIKE UPPER('%". $q ."%') LIMIT 0, 10";

		//echo $sSql;



		$rs=$GLOBALS["conn"]->Execute($sSql);

			
		while ($rs && !$rs->EOF)  {



			//echo '"'.$rs->fields["id"].'": "'.$rs->fields["lib"].'"'.'\n';
				
			$results[] = array(
					'label'    => $rs->fields["lib"],
					'value' => $rs->fields["id"]
						
			);
			$rs->MoveNext();


		}


			
		// modify your http header to json, to help browsers to naturally handle your response with
		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');

		echo json_encode($results);

	}


}elseif($operation=="dofileUpload")
{
	?>
<style type="text/css">
    body{

        margin: 0px;
    }
</style>
<div id="loading" style="display: none;"><img src="/images/Loading_bar.gif" height="30px"></div>
<?php

	if(isset($_FILES['file'])){


        $path=getFilesPath(getParameter("path"),true)."/";
        $errors= array();
        $file_name = $_FILES['file']['name'];
        $file_size =$_FILES['file']['size'];
        $file_tmp =$_FILES['file']['tmp_name'];
        $file_type=$_FILES['file']['type'];
      //  $file_ext=strtolower(end(explode('.',$file_name)));




       if(!ew_CheckFileType($file_name))
       {
           $errors[]='File extension non authorized !';
       }
       /* if($file_size > 2000097152){
            $errors[]='File size must be small than 20 MB';
        }*/
        if(empty($errors)==true){
            // echo $file_tmp;
            move_uploaded_file($file_tmp,$path.$file_name);
            //	echo "Success";

                       ?>
        <script type="text/javascript">
            parent.setuploadvalue_<?=getParameter("field")?>("<?=$file_name?>","<?=getParameter("field")?>");

        </script>
        <?php
        }else{
            print_r($errors);
        }
    }

}elseif($operation=="fileUpload")

{

	?>
<script type="text/javascript" src="/js/jquery-1.8.2.js"></script>
    <style type="text/css">
        body{

            margin: 0px;
        }
    </style>

<div id="loading" style="display: none;"><img src="/images/Loading_bar.gif" height="30px"></div>
<form id="form" action="/portlet.php?app=system&operation=dofileUpload" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="hidden" name="path" value="<?php echo getParameter("path"); ?>" />
    <input type="hidden" name="field" value="<?php echo getParameter("field"); ?>" />



    <input type="submit"  onclick="loading()"/>
    <script type="text/javascript">

        function loading()
        {

            $("#loading").show();
            $("#form").hide();
        }

    </script>
</form>
    <?php
}
elseif ($operation=="getTableComuns")
{
	

	$table=getParameter("table");
	$columns=getTableColumns($table);
	$ret="";
	foreach ($columns as $column)
	{
		
		$ret.= $column.",";

	}
	$ret=substr($ret, 0,strlen($ret)-1); 
	echo $ret;
	
	//echo "ok";
}
elseif ($operation=="changeOrder")
{
	
	MoveObject(getParameter("objectId"),getParameter("table"),getParameter("direction"));
	echo "ok";
}
elseif($operation=="updatetable")
{
	
	$table=getParameter("table");
	$objectId=getParameter("objectId");
	$field=getParameter("field");
	$value=getParameter("value");
	
	ew_LoadRecordset("UPDATE $table set $field='$value' WHERE id=$objectId");
	echo "ok";
	
}
elseif ($operation=="getparentmenu")
{

	if(isset($_GET['term'])) {
		$q = htmlentities($_GET['term']); // protection
			
		$results = array();




		$sSql = "SELECT
portal_menu.id,
portal_objects.lib_$LANG as lib
FROM
portal_objects
INNER JOIN portal_menu ON portal_objects.id = portal_menu.objectId WHERE UPPER(lib_$LANG) LIKE UPPER('%". $q ."%') LIMIT 0, 10";

		//echo $sSql;



		$rs=$GLOBALS["conn"]->Execute($sSql);

			
		while ($rs && !$rs->EOF)  {



			//echo '"'.$rs->fields["id"].'": "'.$rs->fields["lib"].'"'.'\n';
				
			$results[] = array(
					'label'    => $rs->fields["lib"],
					'value' => $rs->fields["id"]
						
			);
			$rs->MoveNext();


		}


			
		// modify your http header to json, to help browsers to naturally handle your response with
		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');

		echo json_encode($results);

	}


}elseif ($operation=="move_portlet")
{
$sSql ="UPDATE portal_portletpage SET `place` = '".$container."', `orderCmpnt` = '".$order."' WHERE `id` =".$coupleId.";";
 // echo $sSql ;
  $rs=$GLOBALS["conn"]->Execute($sSql); 
	  echo "ok";
}elseif ($operation=="order_portlet")
{
//$sSql ="UPDATE portletpage set order='#".$order."'  where id=".$coupleId." ;";
   $rs=$GLOBALS["conn"]->Execute($sSql); 
	  echo "ok";
}elseif ($operation=="remove_portlet")
{
$sSql ="DELETE FROM portal_portletpage where id=".$coupleId." ;";
//echo $sSql;
      $rs=$GLOBALS["conn"]->Execute($sSql); 
	  echo "ok";
}elseif ($operation=="add_portlet")
{

echo addPortlet($pageId,$portletId,$container);

}elseif ($operation=="get_preferences")
{
	$sSql ="SELECT * FROM `portal_portlet_preferences` WHERE `portlet_page_id`=".$coupleId.";";
	$sSql ="Select portal_portlet_preferences_names.query,
	portal_portlet_preferences.name,
	portal_portlet_preferences.value
	From portal_portlet_preferences_names Inner Join
	portal_portlet_preferences On portal_portlet_preferences_names.name =
	portal_portlet_preferences.name Inner Join
	portal_portletpage On portal_portlet_preferences.portlet_page_id =
	portal_portletpage.id And portal_portlet_preferences_names.portlet_id =
	portal_portletpage.portletId
	Where portal_portlet_preferences.portlet_page_id = $coupleId ";
//	echo $sSql ;
	$rs=$GLOBALS["conn"]->Execute($sSql);
	//echo "ok";
	
$file="apps/".getObjByKey("portal_portlet","appurl","id",$portletId).'/editmode.php';
	if (file_exists($file))
	include $file;
	
    loadfile("/js/yamli_api.js","js");
	?>

	<form dir="ltr">
        <b>Portlet UID : </b><?php echo $coupleId; ?> <a target="_blank"  href="/portal/portal_portlet_preferenceslist.php?showmaster=portal_portletpage&id=<?php echo $coupleId; ?>">Edit in Portal</a><br/>
	<fieldset>
	<table>
	<?php
	 while (!$rs->EOF)  {
	 	$name=$rs->fields["name"];
	 	$$name=$rs->fields["value"];
	 //	echo $$name;
	 ?>
	 
	 <tr>
	 
	 <td><label for="<?php echo $rs->fields["name"]; ?>" style="font-weight: bold;"><?php echo $rs->fields["name"]; ?></label></td><td width="20px"></td>
	 <td><?php 
	 $query=$rs->fields["query"];
         $fieldName=$rs->fields["name"]."_".$coupleId;

         $dir="ltr";
         if ($LANG=="AR" && strpos($fieldName,"AR"))  $dir="rtl";
	 if ($query!="") {

         if (strpos($query,"portalId=")) 	$query.=" Order by lib asc";
             else
          	$query.=" and portalId=".$portalId." Order by lib asc";
	 	eval("\$query=\"".$query."\";  ");
	 //	echo $query;


	 	?>
	 <select dir="<?php echo $dir; ?>" name="<?php echo $fieldName; ?>" id="<?php echo $fieldName; ?>" class="text ui-widget-content ui-corner-all" style="min-width:200px">
	 <option  value=""></option>
	 <?php 
	 
	 $rs2=$GLOBALS["conn"]->Execute($query);
	 while (!$rs2->EOF)  {
	 	
	 	if ($rs->fields["value"]==$rs2->fields["value"]) $selected="selected=\"selected\""; else $selected="";
	 	?>
	 	<option <?php echo $selected; ?> value="<?php echo $rs2->fields["value"]; ?>"><?php echo $rs2->fields["lib"]; ?></option>
	 	<?php 
	 	$rs2->MoveNext();
	 }
	 
	 ?>
	 
	 </select>
	 
	 <?php }
	 else {


	 ?><input dir="<?php echo $dir; ?>" type="text" name="<?php echo $fieldName; ?>" id="<?php echo $fieldName; ?>" value="<?php echo $rs->fields["value"]; ?>" class="text ui-widget-content ui-corner-all" style="min-width:200px"/>
	 <?php
     if (strpos($fieldName,"AR"))
         Yamlify($fieldName);

     } ?>
	 </td>
	</tr>
	<tr height="5px;">
	<td colspan="3">
	</td>
	</tr>
	 <?php 
	
	$rs->MoveNext();
	}
	?>
	</table>
	 </fieldset>
	 
	 </form>
		<?php
}elseif ($operation=="export_preferences")
{
	$sSql="SELECT
portal_portlet.appname,
portal_pages.name
FROM
portal_portletpage
INNER JOIN portal_portlet ON portal_portletpage.portletId = portal_portlet.id
INNER JOIN portal_pages ON portal_pages.id = portal_portletpage.pageId
WHERE
portal_portletpage.id =".$coupleId;
	
	//echo $sSql;
	$rs=$GLOBALS["conn"]->Execute($sSql);
	$porltetName=stripAccents($rs->fields["appname"]);
	$pageName=stripAccents($rs->fields["name"]);
	
	$sSql ="SELECT * FROM `portal_portlet_preferences` WHERE `portlet_page_id`=".$coupleId.";";
	$sSql ="Select portal_portlet_preferences_names.query,
	portal_portlet_preferences.name,
	portal_portlet_preferences.value
	From portal_portlet_preferences_names Inner Join
	portal_portlet_preferences On portal_portlet_preferences_names.name =
	portal_portlet_preferences.name Inner Join
	portal_portletpage On portal_portlet_preferences.portlet_page_id =
	portal_portletpage.id And portal_portlet_preferences_names.portlet_id =
	portal_portletpage.portletId
	Where portal_portlet_preferences.portlet_page_id = ".$coupleId.";";
	echo $sSql ;
	$rs=$GLOBALS["conn"]->Execute($sSql);
	//echo "ok";
	$filename="export_".$porltetName."_".$pageName."_".$_SERVER['REQUEST_TIME'].".csv";
	

	$filepath=getFilesPath("tmp_export",true)."/".$filename;
	$fp = fopen($filepath, 'w');
	
	
	
	
	 while (!$rs->EOF)  {
	 	$name=$rs->fields["name"];
	 	$value=$rs->fields["value"];
	 fputcsv($fp, array($name,$value));
	
	$rs->MoveNext();
	}
	fclose($fp);
	
	?>
	Portlet preferences has been succesfully generated, please click on the link bellow to store the file.<br/>
	<a href="<?php echo $filepath; ?>">Download</a>
	<?php 
	
}elseif ($operation=="import_preferences")
{

	
	if (isset($_FILES['file']['name'])){
		
		$target_path = getFilesPath("tmp_import",true)."/";
		
		$target_path = $target_path . basename( $_FILES['file']['name']);
		
		if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
			echo "The file ".  basename( $_FILES['file']['name']).
		    " has been uploaded";
		} else{
			echo "There was an error uploading the file, please try again!";
		}
		
		$sSql="Delete from portal_portlet_preferences where portlet_page_id=".$coupleId;
		$GLOBALS["conn"]->Execute($sSql);
		
		$sSql=" insert into portal_portlet_preferences (`portlet_page_id`,`name`,`value`,`portalId`) values ";
		$row = 1;
		if (($handle = fopen($target_path, "r")) !== FALSE) {
			while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
				$num = count($data);
				$row++;
				for ($c=0; $c < $num; $c++) {
					if ($c==0) $sSql.=" (".$coupleId.",";
				$sSql.="'".$data[$c]."'";
				if ($c==0)  $sSql.=",";
				}
				$sSql.=",$portalId) , ";
				}
				fclose($handle);
				}
				$sSql=substr($sSql, 0,strlen($sSql)-2);
				//echo $sSql; 
				$GLOBALS["conn"]->Execute($sSql);
	}
	?>
	
	<div id="uploadOutput" >
	<form id="uploadForm" method="POST" enctype="multipart/form-data" encoding="multipart/form-data">
	<?php setupForm(); ?>
	<input type="hidden" name="MAX_FILE_SIZE" value="100000">
	File: <input type="file" name="file">

	<input type="submit" value="Submit">
	</form>
	
	<script type="text/javascript">
	
	var options = {
			 beforeSubmit: function(a,f,o) {
		            o.dataType = "html";
		            $('#uploadOutput').html('Submitting...');
		        },
		url:        '<?php echo ew_CurrentUrl(); ?>',
		success: function(data) {
            var $out = $('#uploadOutput');
          
           $out.html( data );
        }
	};
	
	$('#uploadForm').ajaxForm(options);
	</script>
	
	</div>
	<?php
	
}elseif ($operation=="save_preferences")
{
   $GLOBALS["conn"]->BeginTrans();

	$exclusion=array("app","operation","coupleId");

foreach($_REQUEST as $name=>$value)
{

	if (in_array($name,$exclusion)==false) {

		savePortletPreferences($coupleId,$value,$name);


		
	}

   }

 $GLOBALS["conn"]->CommitTrans(); // Commit the change
	//statements

echo "ok";
}
elseif ($operation=="reload_preferences")
{
	reloadPortletPreferences($coupleId);
	
echo "ok";

}elseif ($operation=="generate_css")
{
	
	
	
	
	$sSql ="Select portal_fonts.name As fontltName, ".
	  "portal_fonts.url As fontltUrl, ".
	  "portal.*, ".
	  "fonts1.name As fontarName, ".
	  "fonts1.url As fontarUrl ".
	"From portal Inner Join ".
	  "portal_fonts On fontLtId = portal_fonts.id Inner Join ".
	  "portal_fonts fonts1 On fontArId = fonts1.id ".
	"Where portal.id = ".$portalId;
	Portal_log($sSql);
	$rs=$GLOBALS["conn"]->Execute($sSql);
	
	
	//echo $sSql."<br/>";
	
	
?>
@repeatBackground:<?php echo $rs->fields["repeatBackground"]; ?>;
@fontName:<?php echo $rs->fields["font".$lt."Name"]; ?>;
@colorOne:<?php echo $rs->fields["OneColor"]; ?>;
@colorTwo:<?php echo $rs->fields["TwoColor"]; ?>;
@colorThree:<?php echo $rs->fields["ThreeColor"]; ?>;
@portalBackground :url("./backgrounds/<?php echo $rs->fields["background"]; ?>");
<?php 	
}elseif ($operation=="ckeditorconfig")
{

	
	$sSql ="Select portal_fonts.name As fontltName, ".
	"portal_fonts.url As fontltUrl, ".
	"portal.*, ".
		  "fonts1.name As fontarName, ".
		  "fonts1.url As fontarUrl ".
		"From portal Inner Join ".
		  "portal_fonts On fontLtId = portal_fonts.id Inner Join ".
		  "portal_fonts fonts1 On fontArId = fonts1.id ".
		"Where portal.id = ".$portalId;
	Portal_log($sSql);
	$rs=$GLOBALS["conn"]->Execute($sSql);
	
	$fontltName=$rs->fields["fontltName"];
	$fontltName=str_replace("'", "", $fontltName);
	
	$fontarName=$rs->fields["fontarName"];
	$fontarName=str_replace("'", "", $fontarName);
	
	?>



/*
Copyright (c) 2003-2009, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/

CKEDITOR.editorConfig = function( config )
{
	config.enterMode = CKEDITOR.ENTER_BR;
	// Define changes to default configuration here. For example:
	 config.language = '<?php echo $lang; ?>';
	// config.uiColor = '#40546A';

		config.font_names = "<?php echo $fontltName; ?>;"  +"<?php echo $fontarName; ?>;"  + config.font_names;

	// Configure full toolbar here
	config.toolbar = 'MyToolbar';
	config.toolbar_MyToolbar =
	[
	['Source','-','NewPage','Preview','-','Templates'],
	['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
	['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
	['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
		'/',
	['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
	['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
	['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
	['Link','Unlink','Anchor'],
	['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
		'/',
	['Styles','Format','Font','FontSize'],
	['TextColor','BGColor'],
	['ShowBlocks','-','About']
	];
};
<?php 
}elseif ($operation=="load_css")
{
	
	
	/*$file = getFileContent('/portlet.php?app=system&operation=generate_css', false);
	
	echo $file;*/
	
	
	$sSql ="Select portal_fonts.name As fontltName, ".
	"portal_fonts.url As fontltUrl, ".
	"portal.*, ".
		  "fonts1.name As fontarName, ".
		  "fonts1.url As fontarUrl ".
		"From portal Inner Join ".
		  "portal_fonts On fontLtId = portal_fonts.id Inner Join ".
		  "portal_fonts fonts1 On fontArId = fonts1.id ".
		"Where portal.id = ".$portalId;
	Portal_log($sSql);
	$rs=$GLOBALS["conn"]->Execute($sSql);
	
	
	//echo $sSql."<br/>";


// At more elements as you wish
	if (!$rs->EOF){
        $array = array('fontName' => $rs->fields["font".$lt."Name"],
                       'repeatBackground'=>$rs->fields["repeatBackground"],
	            'fontName'=>$rs->fields["font".$lt."Name"],
	            'colorOne'=>$rs->fields["OneColor"],
	        'colorTwo'=>$rs->fields["TwoColor"],
	        'colorThree'=>$rs->fields["ThreeColor"],
	        'portalBackground'=>"url('".getFileManagerImage('image',$rs->fields["background_file"])."')"
    );
	

    }


	$buffer=getFileContent(ew_DomainUrl().getParameter("file"), FILE_USE_INCLUDE_PATH);

    echo parse_variables($buffer,$array);
	
 //Dynamic SyleSheet 
 
	
//insertCustomCSS($dir);
	
	
}elseif ($operation=="deletePortal")
{
	deletePortal($_REQUEST["url"]);
}
elseif ($operation=="filePicker")
{
	
	$folder=str_replace("../", "",	$_REQUEST["folder"]);
	/*$ext=explode(",", $_REQUEST["ext"]);
	//echo $ext;
if ($handle = opendir($folder)) {
   // echo "Directory handle: $handle\n";
   // echo "Files:\n";
 echo "<ul>";
    while ((false !== ($file = readdir($handle)))) {
    $tmp=explode(".", $file);
    	if ( in_array($tmp[count($tmp)-1], $ext)) {?>
        
        <li ondblclick="changeFile('<?php echo $_REQUEST["fieldName"]; ?>','<?php echo $file; ?>')"><?php echo "$file"; ?></li>
        
        <?php }
    }

    echo "</ul>";
     closedir($handle);
    */
  /*  
    while ($file = readdir($handle)) {
        echo "$file\n";
    }*/

	?>
	<div style="float:left;width:300px;height:300px;overflow-y:scroll ">
	<?php 
	
	$sSql="Select portal_file.filename,portal_file.id
From portal_file Inner Join
  portal_filetype On portal_file.filetypeId = portal_filetype.id
Where portal_file.portalId=".$portalId." and portal_filetype.typename = '".$_REQUEST["type"]."' order by filename";
	//echo $sSql;
	$rs=$GLOBALS["conn"]->Execute($sSql);
	echo "<ul class='filepicker'>";
	while (!$rs->EOF)  {
	 
	$file=$rs->fields["filename"];
	$id=$rs->fields["id"];
	?>
	        
	        <li onmouseover="loadimage('<?php echo $_REQUEST["folder"]."/".$file; ?>')" onclick="changeFile('<?php echo $_REQUEST["fieldName"]; ?>','<?php echo $id; ?>','<?php echo $_REQUEST["folder"]."/".$file; ?>')"><?php echo "$file"; ?></li>
	        
	        <?php
	
		 	$rs->MoveNext();
		 	
		 	
		 }
		 echo "</ul>";
		 ?></div>
		 	<div style="float:right;width: 440px;height:300px;">
		 	<table width="100%"><tr valign="middle"><td width="100%" align="center"><img src="" width="300" id="filepicker_img"></td></tr></table></div>
		 	<?php 
		 	
   

}elseif($operation=="comment")
{
	
	$portletUID=getParameter("portletUID");
	$contentId=getParameter("contentId");
	?>
	
	<div id="Div_Form_<?php echo $portletUID; ?><?php echo $contentId; ?>">
	<h3>Leave a reply</h3>
	
	
	
	<form  method="POST" id="Form_<?php echo $portletUID; ?><?php echo $contentId; ?>">
	<?php setupForm(); ?>
	
	<table width="100%">
	<tr>
	<td width="100px">
	<label>Name</label></td><td><?php formText($portletUID."name",20); ?></td>
	</tr>
	
	
	<tr>
	<td>
	<label>E-mail</label></td><td><?php formText($portletUID."mail",20); ?>
	</td>
	</tr>
	
	<tr >
	<td colspan="2"><?php formTextArea($portletUID."comment",50,10); ?>
	</td>
	</tr>
	
	
	
	
	<tr height="20px">
	<td colspan="2">
	
	</td>
	</tr>
	<tr>
	<td colspan="2">
	
	<img src="/php/captcha/captcha.php?t=<?php echo  time(); ?>" id="<?php echo $portletUID; ?>captcha" /><br/>
	
	
	
	<!-- CHANGE TEXT LINK -->
	<a href="#" onclick="
	    document.getElementById('<?php echo $portletUID; ?>captcha').src='/php/captcha/captcha.php?'+Math.random();
	    document.getElementById('<?php echo $portletUID; ?>captcha-form').focus();"
	    id="change-image">Not readable? Change text.</a><br/><br/>
	
	
	<input type="text" name="<?php echo $portletUID; ?>captcha" id="<?php echo $portletUID; ?>captcha-form" /><?php formError($portletUID."captcha")?><br/>
	</td>
	</tr>
	
	<tr height="20px">
	<td colspan="2">
	
	</td>
	</tr>
	<tr>
	<td colspan="2">
	<input type="submit" value="Valider" name="<?php echo $portletUID; ?>submit">
	</td>
	</tr>
	
	</table>
	
	</form>
	</div>
	
<script type="text/javascript">

var options = { 
	    target:     '#comment_<?php echo $portletUID; ?><?php echo $contentId; ?>', 
	    url:        '<?php echo ew_CurrentUrl(); ?>'
	}; 
	
$('#Form_<?php echo $portletUID; ?><?php echo $contentId; ?>').ajaxForm(options);
</script>
	
	
	<?php
	
	
	
	$error=false;
	if (getParameter($portletUID."submit")!=null){
		/** Validate captcha */
	
		if (isset($_REQUEST[$portletUID.'captcha'])) {
			if (trim(strtolower(getParameter($portletUID."captcha"))) != $_SESSION['captcha']) {
				displayError("Invalid captcha !",$portletUID."captcha");
				// $error=false;
			}
		}
	
		if (getParameter($portletUID."name")==null || getParameter($portletUID."name")=="") displayError("Please enter a valid username !",$portletUID."name");
		if (getParameter($portletUID."mail")==null || ew_CheckEmail(getParameter($portletUID."mail"))==FALSE) displayError("Please enter a valid mail !",$portletUID."mail");
		if (getParameter($portletUID."comment")==null || getParameter($portletUID."comment")=="") displayError("Please enter a comment!",$portletUID."comment");
	
		if ($error==false)
		{
			$name=getParameter($portletUID."name");
			$mail=getParameter($portletUID."mail");
			$comment=getParameter($portletUID."comment");
		

	
			
			$workflowId="NULL";
			$workflow_stageId="NULL";
			$workflow_statusId=2;
	
	
	$sSql="SELECT
portal_authoringtemplate.comment_workflowId,
portal_workflow_stage.workflow_statusId,
portal_workflow_stage.id as stageId
FROM
portal_authoringtemplate
INNER JOIN portal_workflow_stage ON portal_workflow_stage.workflowId = portal_authoringtemplate.comment_workflowId where portal_authoringtemplate.id=".getAuthoringTemplateIdByContent($contentId);
	$rs=$GLOBALS["conn"]->Execute($sSql);
	
	if ($rs->RecordCount()){
	$workflowId=$rs->fields["comment_workflowId"];
	$workflow_stageId=$rs->fields["stageId"];
	$workflow_statusId=$rs->fields["workflow_statusId"];
	}
	
			$sSql="INSERT INTO `portal_comment` (`id` ,`contentId` ,`portalId` ,`text` ,`adddate` ,`workflow_statusId` ,`sender` ,`sender_mail` ,`workflowId` ,`workflow_stageId`)
				VALUES (NULL , '".$contentId."', '".$portalId."', '".$comment."', '".ew_CurrentDateTime()."', '".$workflow_statusId."', '".$name."', '".$mail."',".$workflowId.",".$workflow_stageId.")";
			//echo $sSql."<br/>";
			$GLOBALS["conn"]->Execute($sSql);
			//$newPortalId=getLastId();
			echo "Your comment has been succesfully added !"
			?>
			<script>
			$("#Div_Form_<?php echo $portletUID; ?><?php echo $contentId; ?>").hide();
			
			</script>
			<?php 
		}}
	?>

	<?php 
}elseif($operation=="getComments")
{
	?>
	<?php
	
	$portletUID=getParameter("portletUID");
	$contentId=getParameter("contentId");
	$sSql="Select * from portal_comment where workflow_statusId=2 and contentId=".$contentId;
	$rs=$GLOBALS["conn"]->Execute($sSql);
	while ( !$rs->EOF)  {
	?>
		<img src="/images/noavatar32.png" class="avatar"><div class="sender"><?php echo $rs->fields["sender"] ;?></div>
		<br/><?php echo $rs->fields["text"] ;?>
		<?php
		$rs->MoveNext();
		 if (!$rs->EOF) {?>
		
		<hr/><br/>
		
		<?php
		} 	
		
	}
	
}elseif ($operation=="export_page")
{
	$pageId=getParameter("pageId");
	
	$pagenames=getPageNameById($pageId);
	
	$filename="export_page_".$pagenames."_".$_SERVER['REQUEST_TIME'].".csv";
	
	$filepath=getFilesPath("tmp_export",true)."/".$filename;
	$fp = fopen($filepath, 'w');
	
	
	
	
	
	
	
	//page;
	
	//$rs->fields
	
	
	
	
	
	
	/*$sSql="SHOW COLUMNS FROM portal_pages";
	$columns=$GLOBALS["conn"]->Execute($sSql);
	
	fputs($fp, "[page]\n");
	
	while ( !$columns->EOF)  {
	$name=$columns->fields["Field"];
	$value=$rs->fields[$name];
	
	if ($name=="portalId") $value="[current_portal]";
	if ($name!="id") fputcsv($fp, array($name,$value));
	
	
	$columns->MoveNext();
	}
	*/
	$rs=null;
	export_module("pages",$pageId,$fp,$rs);
	
	
	//layout
	echo $rs->fields["layoutId"];
	export_module("layout",$rs->fields["layoutId"],$fp,$rs);
	
	fclose($fp);
	
	?>
		The Page(s) has been succesfully exported, please click on the link bellow to store the file.<br/>
		<a href="/<?php echo $filepath; ?>">Download</a>
		<?php 
	
	
	/*
	$sSql="SELECT
portal_portlet.appname,
portal_pages.name
FROM
portal_portletpage
INNER JOIN portal_portlet ON portal_portletpage.portletId = portal_portlet.id
INNER JOIN portal_pages ON portal_pages.id = portal_portletpage.pageId
WHERE
portal_portletpage.id =".$coupleId;
	
	//echo $sSql;
	$rs=$GLOBALS["conn"]->Execute($sSql);
	$porltetName=stripAccents($rs->fields["appname"]);
	$pageName=stripAccents($rs->fields["pageName"]);
	
	$sSql ="SELECT * FROM `portal_portlet_preferences` WHERE `portlet_page_id`=".$coupleId.";";
	$sSql ="Select portal_portlet_preferences_names.query,
	portal_portlet_preferences.name,
	portal_portlet_preferences.value
	From portal_portlet_preferences_names Inner Join
	portal_portlet_preferences On portal_portlet_preferences_names.name =
	portal_portlet_preferences.name Inner Join
	portal_portletpage On portal_portlet_preferences.portlet_page_id =
	portal_portletpage.id And portal_portlet_preferences_names.portlet_id =
	portal_portletpage.portletId
	Where portal_portlet_preferences.portlet_page_id = ".$coupleId.";";
	//echo $sSql ;
	$rs=$GLOBALS["conn"]->Execute($sSql);
	//echo "ok";
	$filename="export_".$porltetName."_".$pageName."_".$_SERVER['REQUEST_TIME'].".csv";
	

	$filepath=getFilesPath("tmp_export",true)."/".$filename;
	$fp = fopen($filepath, 'w');
	
	
	
	
	 while (!$rs->EOF)  {
	 	$name=$rs->fields["name"];
	 	$value=$rs->fields["value"];
	 fputcsv($fp, array($name,$value));
	
	$rs->MoveNext();
	}
	fclose($fp);
	
	?>
	Portlet preferences has been succesfully generated, please click on the lick bellow to store the file.<br/>
	<a href="<?php echo $filepath; ?>">Download</a>
	<?php */
	
}elseif ($operation=="barcode")
{
	$barCode=getParameter("code");
	$itemsperline=4;
	$i=0;
	$max=36;
	?>
	<table>
	
	<?php 
while ($i<$max){
	
	if ($i%$itemsperline==0) { ?>  <tr > <?php }?>
	<td><img src="/php/barcodegen/generate.php?code=<?php echo $barCode ; ?>" /></td><td width="20"></td>
	<?php 	  $i++;
 if ($i%$itemsperline==0) { ?></tr><tr height="20"><td colspan="<?php echo $itemsperline; ?>"></td></tr><?php }
 
}
 ?>
	
 </table>
	<?php
}
elseif ($operation=="credentials_config")
{

    ?>
Please select Groups that can view the portlet :
<?php
    $sSql="SELECT * FROM portal_groups WHERE  portalId= $portalId";

    if (EW_DEBUG_ENABLED) echo $sSql."<br/>";
    $rs=$GLOBALS["conn"]->Execute($sSql);
    ?>
    <form id="credentials_config_form">


<table>
<?php
    while ( !$rs->EOF)  {

        $checked="";

        if (getObjByKey("portal_credentials","acces","objectId",$coupleId,"groupId",$rs->fields["id"])=="R") $checked="checked";
        ?>
    <tr><td><?php echo $rs->fields["name"]; ?></td><td><input <?php echo $checked; ?> name="groups" id="group_<?php echo $rs->fields["id"]; ?>_<?php echo $coupleId; ?>" value="<?php echo $rs->fields["id"]; ?>" type="checkbox"/></td></tr>
    <?php

        $rs->MoveNext();
    }
    ?>
</table>
    </form>
<?php
}elseif ($operation=="save_credentials_config")
{

    $GLOBALS["conn"]->BeginTrans();
    $sSql ="SELECT * FROM portal_groups WHERE portalId=$portalId";

    $rs=$GLOBALS["conn"]->Execute($sSql);
    $objectName=getObjByKey("portal_objects","id","name","portal_portletpage");
    while (!$rs->EOF)  {

       $groupId = $rs->fields["id"];
        if (getParameter("group_".$groupId)=="checked"){
      //  echo getParameter("group_".$groupId);

        SetRight($coupleId,$objectName,$groupId,"R");
          //  echo "set ".$groupId;
        }else{
            //
        RevokeRight($coupleId,$objectName,$groupId,"R");
            //echo "revok ".$groupId;
        }
        $rs->MoveNext();
    }
    $GLOBALS["conn"]->CommitTrans();
    echo 'ok';
}elseif($operation=="doUpload")
{
?>
<style type="text/css">
    body{

        margin: 0px;
    }
</style>
<div id="loading" style="display: none;"><img src="/images/Loading_bar.gif" height="30px"></div>
<?php

	if(isset($_FILES['file'])){


        $path=$_REQUEST["path"];
        $errors= array();
        $file_name = $_FILES['file']['name'];
        $file_size =$_FILES['file']['size'];
        $file_tmp =$_FILES['file']['tmp_name'];
        $file_type=$_FILES['file']['type'];
        $file_ext=strtolower(end(explode('.',$_FILES['file']['name'])));




       if(!ew_CheckFileType($file_name))
       {
           $errors[]='File extension non authorized !';
       }
       /* if($file_size > 2000097152){
            $errors[]='File size must be small than 20 MB';
        }*/
        if(empty($errors)==true){
            // echo $file_tmp;
            move_uploaded_file($file_tmp,$path.$file_name);
            //	echo "Success";

            $sSql ="UPDATE portal_contentvalues set Filevalue='$file_name' where id=".getParameter("contentvaluesId");

            $GLOBALS["conn"]->Execute($sSql);
            ?>
        <script type="text/javascript">
            parent.reload(<?php echo getParameter("contentId"); ?>);

        </script>
        <?php
        }else{
            print_r($errors);
        }
    }

}elseif($operation=="formUpload")

{

    ?>
<script type="text/javascript" src="/js/jquery-1.8.2.js"></script>
    <style type="text/css">
        body{

            margin: 0px;
        }
    </style>

<div id="loading" style="display: none;"><img src="/images/Loading_bar.gif" height="30px"></div>
<form id="form" action="/portlet.php?app=system&operation=doUpload" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="hidden" name="path" value="<?php echo getParameter("path"); ?>" />
    <input type="hidden" name="contentId" value="<?php echo getParameter("contentId"); ?>" />
    <input type="hidden" name="contentvaluesId" value="<?php echo getParameter("contentvaluesId"); ?>" />



    <input type="submit"  onclick="loading()"/>
    <script type="text/javascript">

        function loading()
        {

            $("#loading").show();
            $("#form").hide();
        }

    </script>
</form>
    <?php
}elseif ($operation=="exportportal"){
    loadfile("/js/jquery-1.8.2.js","js");
    loadfile("/js/jquery.blockUI.js","js");
//http://ammn.app.com/portlet.php?app=system&operation=exportportal&destfolder=/www/&cleanexport=true

    ?>



<?php

    $targetPortalId=getParameter("targetPortalId");
    
    if ($targetPortalId==null) $targetPortalId=$portalId;

    $today = date("d_m_Y");
    $filename = "exportportal_$today.sql";


    $dir = getFilesPath("tmp_export",true)."/";
/*
    if (file_exists($dir.$filename)) {

        rmdir("/".$dir.$filename);

    }*/

    $fd = fopen($dir.$filename, "w");



    set_time_limit(0);
    //$GLOBALS["conn"]->BeginTrans();




    $Sql ="SELECT
information_schema.`TABLES`.TABLE_NAME as tablename
FROM
information_schema.`TABLES` ,
portal_portal_app,
 portal_app where
information_schema.`TABLES`.TABLE_SCHEMA = DATABASE() AND
portal_portal_app.portalId = $portalId AND portal_app.id = portal_portal_app.appId and
information_schema.`TABLES`.TABLE_NAME  like concat('%', portal_app.`name`, '%') ";

    $rs=$GLOBALS["conn"]->Execute($Sql);

    $j=0;
    $limit=777;
    $limit--;

    fwrite($fd, "SET FOREIGN_KEY_CHECKS=0;\nSET autocommit=0;\nSET unique_checks=0;\n\n". PHP_EOL);
    while (!$rs->EOF && $j<=$limit)  {
        $table=$rs->fields[0];

      //  $table="portal_logins";

$j++;
        $tableComment="\n\n--   ################ TABLE [$table]  ################\n\n ";
    echo $tableComment."<br/>";
        fwrite($fd, $tableComment. PHP_EOL);



       if (getParameter("cleanexport")=="true") fwrite($fd, "TRUNCATE TABLE $table; \nSET FOREIGN_KEY_CHECKS=0;\nSET autocommit=0;\nSET unique_checks=0;\n". PHP_EOL);
        $sSql="SELECT * FROM $table";
        if ($table=="portal")
        {
            $sSql.=" WHERE id=$portalId";
        }else{

          if (ColumnExist($table,"portalId")) $sSql.=" WHERE portalId=$portalId OR portalId IS NULL";
        }
       // echo $sSql."\n";
      $subrs=$GLOBALS["conn"]->Execute($sSql);


        $sSql="SHOW COLUMNS FROM $table";
        $columns=$GLOBALS["conn"]->Execute($sSql);

        $arraycolumns=array();

        while ( !$columns->EOF)  {


            array_push($arraycolumns,$columns->fields["Field"]);

            $columns->MoveNext();
        }




    //print_r($subrs->fields);
        if (getParameter("cleanexport")=="true"){
        $exportSql="INSERT IGNORE INTO $table VALUES";
        }
        $delete=true;
        while ($subrs && !$subrs->EOF)  {

            if (getParameter("cleanexport")!="true"){
                $exportSql="";
                if (ColumnExist($table,"portalId") && $delete==true) {
/*                    $criteria=" is NULL";
                    if ($subrs->fields["portalId"]!="")       $criteria=" = ".$subrs->fields["portalId"];*/
                    $exportSql="DELETE FROM $table where portalId is NULL OR portalId=$targetPortalId;\n";
                    $delete=false;
                }
                $exportSql.="INSERT IGNORE INTO $table VALUES (";
            }else
            $exportSql.="(";

          // echo $table." ".$subrs->fields."<br/>";
          $countColulmns=  count($subrs->fields)/2;

         //   echo "****** ".$subrs->fields["id"]."\n";


         for ($i=0;$i<$countColulmns;)
            {

       //  echo "ok ".$subrs->fields[$i]."<br/>";
                $value=$subrs->fields[$i];
                $value=str_replace("\r", "\\r", $value);
                $value=str_replace("\n", "\\n", $value);
                $value=str_replace("'", "\'", $value);
                if ($targetPortalId && ($arraycolumns[$i]=="portalId" || ($arraycolumns[$i]=="id" && $table=="portal")) &&  $value==$portalId) $value=$targetPortalId;
                ///bug to be fixed later
            /*    if ($tablename=="portal_pages" && $value==null)

                    $exportSql.="NULL";
                else
                    $exportSql.="'$value'";

*/

                if (is_null($subrs->fields[$i]))
                    $exportSql.="NULL";
                else
                $exportSql.="'$value'";

                $i++;
                if ($i!=$countColulmns)  $exportSql.=",";
            }
            $exportSql.=")";
            if (getParameter("cleanexport")!="true" && false){
            $exportSql.= " ON DUPLICATE KEY UPDATE ";

            $i=0;
            foreach($subrs->fields as $key=>$value){
                if ($i%2) {
                    $value=$subrs->fields[$key];
                    $value=str_replace("\r", "\\r", $value);
                    $value=str_replace("\n", "\\n", $value);
                    $value=str_replace("'", "\'", $value);


                    if (is_null($subrs->fields[$key]))
                      $exportSql.="$key=NULL";
                        else
                    $exportSql.="$key='$value'";


                if ($i<($countColulmns*2-1))  $exportSql.=",";
                }
                $i++;
            }
            }

            if (getParameter("cleanexport")=="true"){
                $exportSql.=",";
            }else
            $exportSql.=";";

           /* $countColulmns=  count($subrs->fields)/2;
            for ($i=0;$i<$countColulmns;)
            {
                // echo "''$subrs->fields[0]."\n";
                $exportSql.="'".$subrs->fields[$i]."'";
                $i++;
                if ($i!=$countColulmns)  $exportSql.=",";
            }*/

            //echo $exportSql."<br/>";

            if (getParameter("cleanexport")!="true"){
                fwrite($fd, $exportSql. PHP_EOL);
            }

            $subrs->MoveNext();
        }


        if ($subrs && $subrs->RecordCount()>0 && getParameter("cleanexport")=="true"){
            $exportSql.=";";
            $exportSql=str_replace("),;",");",$exportSql);
            fwrite($fd, $exportSql. PHP_EOL);
        }

        $rs->MoveNext();
    }
   // $GLOBALS["conn"]->CommitTrans();

    fwrite($fd, "SET FOREIGN_KEY_CHECKS=1;SET autocommit=1;SET unique_checks=1;\n\n". PHP_EOL);

    fclose($fd);
    //try toput the file on the distant server


    $file = $dir.$filename;

//zip the file

    $files_to_zip = array(
        $file
    );
//if true, good; if false, zip creation failed
    $result = create_zip($files_to_zip, $file.".zip",true);

    if ($result){
      //  rmdir("/".$file);

        $file = $file.".zip";

    $remote_file = $filename.".zip";
    $destdir=EW_PORTAL_FTP_PATH.getFilesPath("tmp_import",true)."/";
    if (!file_exists($file)) {

        echo "File to Upload Not Found !";

    }else{


// set up basic connection
        $conn_id = ftp_connect(EW_PORTAL_HOST);

        // login with username and password
        $login_result = ftp_login($conn_id, EW_PORTAL_FTP_USER, EW_PORTAL_FTP_PASSWORD);
        ftp_pasv($conn_id, true);
// upload a file

        if (ftp_put($conn_id, $destdir.$remote_file, $file, FTP_BINARY)) {
        echo "successfully uploaded $file<br/>\n";
    } else {
        echo "There was a problem while uploading $file<br/>\n";
            exit();
    }

// close the connection
    ftp_close($conn_id);
        echo "Upload Finished<br/>";

        if (getParameter("import")=="true")
        {


            $output = file_get_contents('http://'.EW_PORTAL_URL.'/portlet.php?app=system&operation=updateportal&file='.$remote_file);
            echo $output;


        }


    }}else{
        echo "There was a problem while zipping the file <br/>\n";

    }
//exit();
  header('Location: /portal/portallist.php');
}elseif ($operation=="updateportal"){

    set_time_limit(0);

    $filename=getParameter("file");


    $dir = getFilesPath("tmp_import",true)."/";
echo getFilesPath("tmp_import",true);
    chdir(getFilesPath("tmp_import",true));
    $dir=getcwd();

    $files1 = scandir($dir);


    print_r($files1);
    $dir="";

    if (!file_exists($dir.$filename)) {

       echo "File Not Found !";
exit();
    }else{


        if (unzip($dir.$filename,getcwd()))
        {
            $file=str_replace(".zip","",$dir.$filename);
        $fd = fopen($file, "r");


           $GLOBALS["conn"]->BeginTrans();
        while ($line = fgets($fd)) {
           echo "Executing Query<br/> $line <br/>";
          $GLOBALS["conn"]->Execute($line);

        }


        fclose($fd);
           $GLOBALS["conn"]->CommitTrans();
        }else{

            echo "Problem occured during unzip !";
            exit();
        }
    }
   //header('Location: /portal/portallist.php');

}elseif ($operation=="fixcontentvalues"){

    set_time_limit(0);


  $GLOBALS["conn"]->BeginTrans();

    $sSql="SELECT * FROM portal_content where portalId=$portalId";


    echo $sSql;
    $subrs=$GLOBALS["conn"]->Execute($sSql);

    //print_r($subrs->fields);
    while (!$subrs->EOF)  {


                $contentId=$subrs->fields["id"];

      //  $tportalId=getObjByKey("portal_content","portalId","id",$contentId);
        $sql="UPDATE portal_contentvalues SET portalId=$portalId WHERE contentId=$contentId";
        echo $sql;
        $GLOBALS["conn"]->Execute($sql);
        $subrs->MoveNext();
    }

  $GLOBALS["conn"]->CommitTrans();
    //header('Location: /portal/portallist.php');
}elseif ($operation=="fixportletpreferences"){

    set_time_limit(0);


    $GLOBALS["conn"]->BeginTrans();

    $sSql="SELECT * FROM portal_portlet_preferences where portalId=0";
    $rs=$GLOBALS["conn"]->Execute($sSql);

    //print_r($subrs->fields);
    while (!$rs->EOF)  {


        $portlet_page_id=$rs->fields["portlet_page_id"];

        $tportalId=getObjByKey("portal_portletpage","portalId","id",$portlet_page_id);
        $sql="UPDATE portal_portlet_preferences SET portalId=$tportalId WHERE portlet_page_id=$portlet_page_id";
        echo $sql."<br/>";
        $GLOBALS["conn"]->Execute($sql);
        $rs->MoveNext();
    }

   $GLOBALS["conn"]->CommitTrans();
    //header('Location: /portal/portallist.php');
}
elseif ($operation=="fixportletpage"){

    set_time_limit(0);


    //$GLOBALS["conn"]->BeginTrans();

    $sSql="SELECT * FROM portal_portletpage where portalId is NULL";
    $rs=$GLOBALS["conn"]->Execute($sSql);

    //print_r($subrs->fields);
    while (!$rs->EOF)  {


        $page_id=$rs->fields["pageId"];

        $tportalId=getObjByKey("portal_pages","portalId","id",$page_id);
        $sql="UPDATE portal_portletpage SET portalId=$tportalId WHERE pageId=$page_id";
        echo $sql."<br/>";
        $GLOBALS["conn"]->Execute($sql);
        $rs->MoveNext();
    }

    // $GLOBALS["conn"]->CommitTrans();
    //header('Location: /portal/portallist.php');
}elseif($operation=="createbulkusers")
{




    set_time_limit(0);




    $target_path = getFilesPath("tmp_import",true)."/";
    $filename=basename( $_FILES['file']['name']);
    $file=$target_path.$filename;

    if (isset($_FILES['file']['name'])){





        if(move_uploaded_file($_FILES['file']['tmp_name'], $file)) {
            echo "The file ".  basename( $_FILES['file']['name']). " has been uploaded";
        } else{
            echo "There was an error uploading the file, please try again!";
        }





    if (!file_exists($file)) {

        echo "File Not Found !";

    }else{


        $groups=preg_split("/,/",getParameter("groups"));
        for ($i=0;$i<count($groups);$i++)
        {
          $groups[$i]=  getObjByKey("portal_groups","id","name",$groups[$i],"portalId",$portalId);

        }
            $fd = fopen($file, "r");


            $GLOBALS["conn"]->BeginTrans();
            while ($line = fgets($fd)) {
                $params=preg_split("/,/",$line);

              $userId= addPortalUser($params[1],$params[1],$params[0],$portalId,1,1);
                echo "add user $userId <br/>";

                for ($i=0;$i<count($groups);$i++)
                {
                    addGroupToUser($userId,$groups[$i]);

                }

            }


            fclose($fd);
            $GLOBALS["conn"]->CommitTrans();

    }

    }
    //header('Location: /portal/portal_loginslist.php');
}elseif($operation=="fixportletrights")
{
//http://cjm.app.com/portlet.php?app=system&operation=fixportletrights&groups=Anonymous,
    $GLOBALS["conn"]->BeginTrans();

echo "fixportletrights";
    $groups=preg_split("/,/",getParameter("groups"));
    for ($i=0;$i<count($groups);$i++)
    {
        $groups[$i]=  getObjByKey("portal_groups","id","name",$groups[$i],"portalId",$portalId);

    }

    $sSql="SELECT * FROM portal_portletpage where portalId=$portalId";
    $rs=$GLOBALS["conn"]->Execute($sSql);

    //print_r($subrs->fields);
    while (!$rs->EOF)  {
            $id=$rs->fields["id"];

        for ($i=0;$i<count($groups);$i++)
        {

            $groupId=$groups[$i];
            SetRight($id,getObjByKey("portal_objects","id","name","portal_portletpage"),$groupId,$right);

        }



        $rs->MoveNext();
    }

    $GLOBALS["conn"]->CommitTrans();

    //header('Location: /portal/portallist.php');
}elseif($operation=="test")
{

    ?>
<script type="text/javascript" src="/js/yamli_api.js"></script>


    <input type="text" id="textbox_id">


<?php
    Yamlify("textbox_id");

}elseif ($operation="setportletprefs")
{



    if (isset($_FILES['file']['name'])){

        $target_path = getFilesPath("tmp_import",true)."/";

        $target_path = $target_path . basename( $_FILES['file']['name']);

        if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
            echo "The file ".  basename( $_FILES['file']['name']).
                " has been uploaded";
        } else{
            echo "There was an error uploading the file, please try again!";
        }

        $values="";
        $row = 1;
        if (($handle = fopen($target_path, "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                $num = count($data);
                $row++;
                for ($c=0; $c < $num; $c++) {
                    if ($c==0) $values.=" (##coupleId##,";
                    $values.="'".$data[$c]."'";
                    if ($c==0)  $values.=",";
                }
                $values.=",$portalId) , ";
            }
            fclose($handle);
        }
        $values=substr($values, 0,strlen($values)-2);
    }








    $name=getParameter("name");
    $value=getParameter("value");
    $sSql="SELECT
portal_portletpage.id
FROM
portal_portletpage
INNER JOIN portal_portlet_preferences ON portal_portlet_preferences.portlet_page_id = portal_portletpage.id
WHERE
portal_portletpage.portalId = $portalId AND
portal_portlet_preferences.`name` = '$name' AND
portal_portlet_preferences.`value` = '$value'";
    $rs=$GLOBALS["conn"]->Execute($sSql);

    $GLOBALS["conn"]->BeginTrans();
    //print_r($subrs->fields);
    while (!$rs->EOF)  {
        $coupleId=$rs->fields["id"];

      // echo $id."<br/>";
    $newvalues=str_replace("##coupleId##",$coupleId,$values);


        $sSql="Delete from portal_portlet_preferences where portlet_page_id=".$coupleId;
    //    echo $sSql."<br/>";
        $GLOBALS["conn"]->Execute($sSql);

        $sSql=" insert into portal_portlet_preferences (`portlet_page_id`,`name`,`value`,`portalId`) values $newvalues";

      //  echo $sSql."<br/>";
        $GLOBALS["conn"]->Execute($sSql);



        $rs->MoveNext();
    }

    $GLOBALS["conn"]->CommitTrans();

    //header('Location: /portal/portallist.php');
}elseif($operation=="fixapppreferences")
{


    $sql="select * from portal_portal_app_preferences where portalId is NULL";


    $rs=$GLOBALS["conn"]->Execute($sql);

    $GLOBALS["conn"]->BeginTrans();
    //print_r($subrs->fields);
    while (!$rs->EOF)  {


        $ppaid=$rs->fields["portal_portal_appId"];


        $targetPortalId=getObjByKey("portal_portal_app","portalId","id",$ppaid);


        $sSql="update portal_portal_app_preferences set portalId=$targetPortalId where portal_portal_appId=$ppaid";

      echo $sSql."<br/>";
        $GLOBALS["conn"]->Execute($sSql);



        $rs->MoveNext();
    }

    $GLOBALS["conn"]->CommitTrans();


}

	/*   while ( !$rs->EOF)  { 
   
  
 echo "le bien : ".$rs->fields["title_FR"]." ville :".$rs->fields["lib_lt"]."<br/>";
    $rs->MoveNext();  
  }*/
/*
echo "ok";
$sql="SELECT DEFAULT(id) as test FROM (SELECT 1) AS dummy LEFT JOIN portal_pages ON True LIMIT 1 ; ";
       $subrs= $GLOBALS["conn"]->Execute($sql);
echo is_null($subrs->fields["test"])."/";

*/
include 'portlet_footer.php';
?>